package fafmessenger.boundary;

import java.util.ArrayList;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;
import fafmessenger.control.InboxController;
import fafmessenger.entity.Contact;

public class InboxGUI extends ListActivity {
	private InboxController inboxController;
	private ArrayList<Contact> contactsBeingShowed;
	public ProgressDialog progressDialog;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        try {
        inboxController = new InboxController(this);
        } catch (Exception e) {
	Log.e("ERRORRRR", e.getMessage());
}
        
	        contactsBeingShowed = inboxController.getAllContactsWithMessages();
	        setListAdapter(new OrderAdapter(this, R.layout.row_contact, contactsBeingShowed));

        ListView contactList = getListView();
        contactList.setTextFilterEnabled(true);
        contactList.setOnItemClickListener(new OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        		Contact c = contactsBeingShowed.get(position);

        		Intent in = new Intent(InboxGUI.this, ConversationGUI.class);
        		in.putExtra("nickname", c.getNickname());
        		in.putExtra("mobilenumber", c.getMobilenumber());
        		InboxGUI.this.startActivity(in);       		
        	}
        });
        
        inboxController.register();
    }
  
    
    @Override
    public void onPause(){
    	super.onPause();
    }
    
    @Override
    public void onResume(){
    	super.onResume();
    	contactsBeingShowed = inboxController.getAllContactsWithMessages();
        setListAdapter(new OrderAdapter(this, R.layout.row_contact, contactsBeingShowed));
    	
    }
    
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.new_message:
        	Intent in = new Intent(InboxGUI.this, NewMessageGUI.class);
        	InboxGUI.this.startActivity(in);       	
            return true;
            
        case R.id.refresh:        	
        	RefreshThread thread = new RefreshThread();
        	
        	progressDialog = ProgressDialog.show(this, "Please wait...", "Refreshing", true, false);
        	
        	thread.start();
            return true;
            
        case R.id.delete_all:
        	inboxController.deleteAllMessages();
        	contactsBeingShowed = inboxController.getAllContactsWithMessages();
            setListAdapter(new OrderAdapter(this, R.layout.row_contact, contactsBeingShowed));
        	
        	Toast toast = Toast.makeText(this, "All messages have been deleted.", 10);
        	toast.show();
        	return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
    public void refreshListAdapter() {
    	setListAdapter(new OrderAdapter(this, R.layout.row_contact, contactsBeingShowed));
    }
    
    private class RefreshThread extends Thread {
    	@Override
    	public void run() {
    		boolean result = inboxController.refresh();
        	
        	if (result) {
        		contactsBeingShowed = inboxController.getAllContactsWithMessages();
        	}
        	
        	handler.sendEmptyMessage(0);
    	}
    	
    	private Handler handler = new Handler() {
            @Override
            public void handleMessage(android.os.Message msg) {
            	progressDialog.dismiss();
            	refreshListAdapter();
            }
    	};
    }
    
    private class OrderAdapter extends ArrayAdapter<Contact> {

        private ArrayList<Contact> contactsWithMessages;

        public OrderAdapter(Context context, int textViewResourceId, ArrayList<Contact> contactsWithMessages) {
                super(context, textViewResourceId, contactsWithMessages);
                this.contactsWithMessages = contactsWithMessages;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
                View v = convertView;
                if (v == null) {
                    LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    v = vi.inflate(R.layout.row_contact, null);
                }
                Contact c = contactsWithMessages.get(position);
                if (c != null) {
                        TextView tt = (TextView) v.findViewById(R.id.toptext);
                        TextView bt = (TextView) v.findViewById(R.id.bottomtext);
                        if (tt != null) {
                              tt.setText("Name: " + c.getMobilenumber());                            }
                        if(bt != null){
                        	if (c.getMessages().get(c.getMessages().size()-1).getBody().length() > 20 ){
                        		bt.setText("Last message: " +c.getMessages().get(c.getMessages().size()-1).getBody().substring(0, 17)+"...");
                        	}
                        	
                        	else{
                              bt.setText("Last message: " +c.getMessages().get(c.getMessages().size()-1).getBody());
                        	}
                        }
                }
                return v;
        }
    }
}